﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace UstavCSharpServer
{
    class UstavServer
    {
        const int MESSAGE_SIZE = 4096;

        private TcpListener tcpListener;
        private Thread listenThread;
        
        bool isServerEnabled = false;

        public void Start(int port)
        {
            tcpListener = new TcpListener(IPAddress.Any, port);
            listenThread = new Thread(new ThreadStart(ListenForClients));
            listenThread.Start();
        }

        public void Stop()
        {
            if (isServerEnabled)
            {
                isServerEnabled = false;

                tcpListener.Stop();
            }
        }

        private void ListenForClients()
        {
            tcpListener.Start();

            while (isServerEnabled)
            {
                try
                {
                    // Blocks until a client has connected to the server
                    TcpClient tcpClient = tcpListener.AcceptTcpClient();

                    NetworkStream clientStream = tcpClient.GetStream();
                    byte[] message = new byte[MESSAGE_SIZE];
                    int bytesRead = 0;

                    // Blocks until a client sends a message
                    bytesRead = clientStream.Read(message, 0, MESSAGE_SIZE);

                    if (bytesRead == 0)
                    {
                        // The client has disconnected from the server
                        break;
                    }

                    // Message has successfully been received
                    ASCIIEncoding encoder = new ASCIIEncoding();
                    HandleClientComm(encoder.GetString(message, 0, bytesRead));

                    tcpClient.Close();
                }
                catch
                {
                    // A blocking operation was interrupted by a call to WSACancelBlockingCall
                    // Or some other socket error has occured            
                    break;
                }
            }
        }

        private void HandleClientComm(string message)
        {
            //textBox1.Text += message;
        }
    }
}
